<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use Exception;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;
use think\Request;
use think\Response;

use app\model\Notice as NoticeModel;

use app\validate\Notice as NoticeValidate;

class Notice extends BaseController
{
    protected NoticeModel $model;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new NoticeModel();
    }

    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function index():Response
    {
        $params = $this->request->param();
        $where = [];
        if (!empty($params['keywords'])) {
            $where[] = ['title|keywords' , 'like' , '%' . $params['keywords'] . '%'];
        }
        if (isset($params['state']) && $params['state'] !== '') {
            $where['state'] = $params['state'];
        }
        if (!empty($params['type'])) {
            $where['type'] = $params['type'];
        }

        try {
            $query = $this->model->where($where);
            $count = $query->count();
            $list = $query->page($this->page , $this->pageSize)->order('id DESC')->select();
            $list = $list->map(function ($item) {
                $item['type_text'] = NoticeModel::TYPE_LIST[$item['type']];
                return $item;
            });
            $data = [
                'pageSize' => $this->pageSize ,
                'page'     => $this->page ,
                'total'    => $count ,
                'list'     => $list ,
            ];

            return $this->success('success' , $data);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return $this->error('error');
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return Response
     */
    public function create():Response
    {
        $params = $this->request->param();
        $validate = new NoticeValidate();
        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }
        $info   = $this->model::create($params);
        if ($info->isEmpty()) {
            return $this->error();
        }

        return $this->success('success' , $info->toArray());
    }


    /**
     * 显示指定的资源
     *
     * @return Response
     */
    public function read():Response
    {
        $id = $this->request->param('id/d' , 0);
        if (!$id) {
            return $this->error('parameter error');
        }
        try {
            $info = $this->model->find($id);
            if ($info->isEmpty()) {
                return $this->error('data does not exist');
            }
            return $this->success('success' , $info->toArray());
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function edit(Request $request):Response
    {
        $params = $request->param();
        if (empty($params['id'])) {
            return $this->error('parameter error');
        }
        try {
            $info = $this->model->find($params['id']);
            if ($info->isEmpty()) {
                return $this->error('data does not exist');
            }
            foreach ($params as $key => $value) {
                if ($key === 'user_group') {
                    $info->$key = implode(',' , $value);
                } else {
                    $info->$key = $value;
                }
            }
            $info->save();

            return $this->success('success' , $info->toArray());
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return $this->error($e->getMessage());
        }
    }


    /**
     * 删除指定资源
     *
     * @param int $id
     *
     * @return Response
     */
    public function delete(int $id):Response
    {
        if (empty($id)) {
            return $this->error('parameter error');
        }
        try {
            $result = $this->model::destroy($id);
            if ($result) {
                return $this->success();
            }
            return $this->error();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
